//
//  HMPlayingViewController.m
//  04-黑马音乐
//
//  Created by apple on 15-3-29.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "HMPlayingViewController.h"
#import "HMAutioTool.h"
#import "UIView+AdjustFrame.h"
#import "HMMusic.h"
#import "HMMusicTool.h"
#import "HMLrcView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface HMPlayingViewController () <AVAudioPlayerDelegate>

- (IBAction)exit;
/*!
 *  歌词按钮点击
 */
- (IBAction)lrcOrPic:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIImageView *singerImage;
/*!
 *  歌曲名Lable
 */
@property (weak, nonatomic) IBOutlet UILabel *songLabel;
/*!
 *  歌手的Lable
 */
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIButton *sliderButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sliderLeftCon;
/*!
 * 拖动时时间Lable
 */
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
/*!
 *  歌词View
 */
@property (weak, nonatomic) IBOutlet HMLrcView *lrcView;

@property (nonatomic, strong) HMMusic *playingMusic;

@property (nonatomic, strong) AVAudioPlayer *player;

/*!
 *  进度条定时器,
 */
@property (nonatomic, strong) NSTimer *progressTimer;
/*!
 *  歌词跟新定时器
 */
@property (nonatomic, strong) CADisplayLink *lrcTimer;
// 进度条手势
- (IBAction)tapProgressBg:(UITapGestureRecognizer *)sender;
// 拖拽按钮手势
- (IBAction)panSliderButton:(UIPanGestureRecognizer *)sender;
// 播放或者暂停按钮
@property (weak, nonatomic) IBOutlet UIButton *playOrPauseButton;

/*!
 *  播放或者暂停按钮
 */
- (IBAction)playOrPause;
/*!
 *  上一首
 */
- (IBAction)previous;
/*!
 *  下一首
 */
- (IBAction)next;

@end

@implementation HMPlayingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.currentTimeLabel.layer.cornerRadius = 5.0;
    self.currentTimeLabel.layer.masksToBounds = YES;
}


#pragma mark - 公共方法
#pragma mark 显示控制器
- (void)show
{
    // 0.如果点击的新歌曲,不是之前的歌曲,则初始化
    if (self.playingMusic && self.playingMusic != [HMMusicTool playingMusic]) {
        [self stopPlayingMusic];
    }
    
    // 1.取出主窗口,将View添加进来
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.view.frame = window.bounds;
    [window addSubview:self.view];
    window.userInteractionEnabled = NO;
    
    // 2.执行动画
    self.view.y = self.view.height;
    [UIView animateWithDuration:0.5 animations:^{
        self.view.y = 0;
    } completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
        
        // 3.设置音乐数据
        [self startPlayingMusic];
    }];
}

#pragma mark 退出控制器
- (IBAction)exit {
    // 停止定时器
    [self removeProgressTimer];
    [self removeLrcTimer];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        self.view.y = self.view.height;
    }];
}

- (IBAction)lrcOrPic:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.lrcView.hidden = !self.lrcView.hidden;
    if (self.lrcView.hidden) {
        [self removeLrcTimer];
    }else {
        [self addLrcTimer];
    }

}

#pragma mark - 私有方法
#pragma mark 播放歌曲
- (void)startPlayingMusic
{
    // 0.如果就是正在播放的歌曲,不需要重新设置
    if (self.playingMusic == [HMMusicTool playingMusic])
    {
        // 开启定时器
        [self addProgressTimer];
        [self addLrcTimer];
        return;
    }
    
    // 1.取出当前正在播放的歌曲
    HMMusic *playingMusic = [HMMusicTool playingMusic];
    self.playingMusic = playingMusic;
    
    // 2.设置歌曲相关的信息
    self.singerImage.image = [UIImage imageNamed:playingMusic.icon];
    self.songLabel.text = playingMusic.name;
    self.singerLabel.text = playingMusic.singer;
    
    // 3.开始播放歌曲
    self.player = [HMAutioTool playMusicWithName:playingMusic.filename];
    self.player.delegate = self;
    self.timeLabel.text = [self stringWithTime:self.player.duration];
    
    
    // 6.设置歌词
    self.lrcView.lrcName = self.playingMusic.lrcname;
    
    // 4.开启定时器
    [self addProgressTimer];
    [self addLrcTimer];
    
    // 5.设置播放按钮的状态
    self.playOrPauseButton.selected = NO;
    
    
    // 7.切换锁屏界面
    [self updateLockScreenMusic];
}
#pragma mark 停止播放歌曲
- (void)stopPlayingMusic
{
    // 3.停止定时器
    [self removeProgressTimer];
    [self removeLrcTimer];
    
    // 1.重置界面内容
    self.singerImage.image = [UIImage imageNamed:@"play_cover_pic_bg"];
    self.songLabel.text = nil;
    self.singerLabel.text = nil;
    self.timeLabel.text = nil;
    
    // 2.停止之前的歌曲
    [HMAutioTool stopMusicWithName:self.playingMusic.filename];
    
    
    
    // 4.设置按钮播放的状态
    self.playOrPauseButton.selected = YES;
}

#pragma mark 锁屏界面的内容
- (void)updateLockScreenMusic
{
    // 1.获取播放信息的单例
    MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
    
    // 2.设置要放内容的字典
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[MPMediaItemPropertyAlbumTitle] = self.playingMusic.name;
    info[MPMediaItemPropertyArtist] = self.playingMusic.singer;
    
    info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:self.playingMusic.icon]];
    info[MPMediaItemPropertyPlaybackDuration] = @(self.player.duration);
    info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(self.player.currentTime);
    
    // 3.设置播放信息
    [center setNowPlayingInfo:info];
    
    // 4.开始监听远程控制事件
    // 4.1.成为第一响应者
    [self becomeFirstResponder];
    
    // 4.2.开始监控(会让第一响应者去监听事件)
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    /*
     UIEventSubtypeRemoteControlPlay                 = 100,
     UIEventSubtypeRemoteControlPause                = 101,
     UIEventSubtypeRemoteControlStop                 = 102,
     UIEventSubtypeRemoteControlTogglePlayPause      = 103,
     UIEventSubtypeRemoteControlNextTrack            = 104,
     UIEventSubtypeRemoteControlPreviousTrack        = 105,
     UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
     UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
     UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
     UIEventSubtypeRemoteControlEndSeekingForward    = 109,
     */
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self playOrPause];
            break;
            
        case UIEventSubtypeRemoteControlNextTrack:
            [self next];
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self previous];
            break;
        default:
            break;
    }
}

#pragma mark 时间转字符串
- (NSString *)stringWithTime:(NSTimeInterval)time
{
    NSInteger min = time / 60;
    NSInteger second = (NSInteger)time % 60;
    
    return [NSString stringWithFormat:@"%02ld:%02ld", min, second];
}

#pragma mark -进度条定时器操作
- (void)addProgressTimer
{
    if (!self.player.playing) return;
    
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
    
    [self updateInfo];
}

- (void)removeProgressTimer
{
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

- (void)updateInfo
{
    // 1.获取当前的进度
    CGFloat progress = self.player.currentTime / self.player.duration;
    self.sliderLeftCon.constant = progress * (self.view.width - self.sliderButton.width);
    
    // 2.设置滑块上的文字
    [self.sliderButton setTitle:[self stringWithTime:self.player.currentTime] forState:UIControlStateNormal];
    
    // 3:跟新锁频界面
    [self updateLockScreenMusic];
}

#pragma mark -歌词跟新定时器操作
/*!
 *  歌词定时器
 */
- (void)addLrcTimer
{
    if (!self.player.playing || self.lrcView.hidden == YES || self.view.y == self.view.height) return;
    
    self.lrcTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrc)];
    [self.lrcTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    [self updateInfo];
}

/*!
 *  移除歌词跟新定时器
 */
- (void)removeLrcTimer
{
    [self.lrcTimer invalidate];
    self.lrcTimer = nil;
}

/*!
 *  歌词实时传值
 */
- (void)updateLrc
{
    // 没有显示歌词,不需要传值.直接返回
    if (!self.lrcTimer) return;
    self.lrcView.currentTime = self.player.currentTime;
}

#pragma mark - 手势操作
/**
 *  点击进度条背景
 */
- (IBAction)tapProgressBg:(UITapGestureRecognizer *)sender {
    // 1.获取用户点击的点
    CGPoint point =  [sender locationInView:sender.view];
    
    // 2.设置滑块到用户点击的点
    self.sliderLeftCon.constant = point.x - self.sliderButton.width * 0.5;
    if (self.sliderLeftCon.constant >= self.view.width - self.sliderButton.width) {
        self.sliderLeftCon.constant = self.view.width - self.sliderButton.width - 1;
    }
    
    // 3.设置播放进度
    CGFloat progress = self.sliderLeftCon.constant / (self.view.width - self.sliderButton.width);
    self.player.currentTime = self.player.duration * progress;
    
    // 4.立即更新进度
    [self updateInfo];
}

/**
 *  滑块的拖拽
 */
- (IBAction)panSliderButton:(UIPanGestureRecognizer *)sender {
    
    CGFloat progress = self.sliderLeftCon.constant / (self.view.width - self.sliderButton.width);
    NSTimeInterval currentTime = self.player.duration * progress;
    
    if (sender.state == UIGestureRecognizerStateBegan) {
        // 显示"正在拖动时间Lable"
        self.currentTimeLabel.hidden = NO;
        // 拖拽中定时器移除,不跟新进度条
        [self removeProgressTimer];
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        // 隐藏"正在拖动时间Lable"
        self.currentTimeLabel.hidden = YES;
        
        // 3.设置播放进度
        self.player.currentTime = currentTime;
        
        if (self.playOrPauseButton.selected == NO) {
            [self addProgressTimer];
        }
    }
    
    // 用户拖拽了多长
    CGPoint point = [sender translationInView:sender.view];
    [sender setTranslation:CGPointZero inView:sender.view];
    self.sliderLeftCon.constant += point.x;
    
    if (self.sliderLeftCon.constant < 0) {
        self.sliderLeftCon.constant = 0;
    } else if (self.sliderLeftCon.constant > self.view.width - self.sliderButton.width) {
        self.sliderLeftCon.constant = self.view.width - self.sliderButton.width - 1;
    }
    
    // 设置按钮上的文字
    [self.sliderButton setTitle:[self stringWithTime:currentTime] forState:UIControlStateNormal];
    // 跟新"正在拖动时间Lable"
    self.currentTimeLabel.text = self.sliderButton.titleLabel.text;
}

#pragma mark - 歌曲的控制方法
#pragma mark 播放或者暂停
- (IBAction)playOrPause {
    if (self.player.isPlaying) {
        self.playOrPauseButton.selected = YES;
        
        // 暂停歌曲
        [self.player pause];
        // 移除定时器,不跟新进度条
        [self removeProgressTimer];
        [self removeLrcTimer];
    } else {
        self.playOrPauseButton.selected = NO;
        
        // 播放歌曲
        [self.player play];
        // 增加进度条
        [self addProgressTimer];
        [self addLrcTimer];
        
        // 锁屏状态设置
        [self updateLockScreenMusic];
    }
}
#pragma mark 上一首
- (IBAction)previous {
    // 1.停止播放
    [self stopPlayingMusic];
    
    // 2.上一首歌曲
    [HMMusicTool previousMusic];
    
    // 3.播放歌曲
    [self startPlayingMusic];
}
#pragma mark 下一首
- (IBAction)next {
    // 1.停止播放
    [self stopPlayingMusic];
    
    // 2.下一首歌曲
    [HMMusicTool nextMusic];
    
    // 3.播放歌曲
    [self startPlayingMusic];
}

#pragma mark - AVAudioPlayer的代理方法
/*!
 *  播放器播完时调用
 *
 *  @param player 播放器
 *  @param flag   成功播放的标识
 */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    // 播完跳下一首
    if (flag) {
        [self next];
    }
}

/*!8.0以前才调用
 *  播放器被打断
 *
 *  @param player 播放器
 */
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
    [self playOrPause];
}

/*!8.0版本以前用,
 *  当歌曲播放结束段,继续播放
 *
 *  @param player <#player description#>
 */
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
    [self playOrPause];
}
@end
